package com.qn.visitor.analyze;


import com.alibaba.fastjson2.JSON;
import com.qn.visitor.analyze.filter.FilterContext;
import com.qn.visitor.analyze.filter.strategy.IAnalyzeFilter;
import com.qn.visitor.analyze.resolver.IResolver;
import com.qn.visitor.model.UserVisitorRequest;
import com.qn.visitor.model.bo.AnalyzeBo;
import com.qn.visitor.model.bo.analyze.ClientLanguageModel;
import com.qn.visitor.model.bo.analyze.IpAddressModel;
import com.qn.visitor.model.bo.analyze.UserAgentModel;
import com.qn.visitor.model.bo.intercept.InterceptSource;
import com.qn.visitor.utils.SaltMd5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
/**
 * qingniu-cloud user source analysis
 *
 * @Author: TXG
 * @Date: 2024/6/11
 * @Version V0.0.2
 */
@Component
public class AnalyzeEngine {

    @Autowired
    IResolver<List<ClientLanguageModel>> clResolver;
    @Autowired
    IResolver<IpAddressModel> ipResolver;
    @Autowired
    IResolver<UserAgentModel> uaResolver;
    @Autowired
    FilterContext filterContext;

    public AnalyzeBo execute(UserVisitorRequest uvrBo) throws Exception {
        AnalyzeBo analyzeBo = new AnalyzeBo();
        analyzeBo.setUvr(uvrBo);
        //生成Hash
        analyzeBo.setClHash(SaltMd5Util.md5(uvrBo.getClientLanguage()));
        analyzeBo.setUaHash(SaltMd5Util.md5(JSON.toJSONString(uvrBo.getUserAgent())));
        analyzeBo.setIpHash(uvrBo.getClientIp());

        //使用单例模式获取 对应的布隆过滤器
        IAnalyzeFilter clFilter = filterContext.clInstance();
        IAnalyzeFilter ipFilter = filterContext.ipInstance();
        IAnalyzeFilter uaFilter = filterContext.uaInstance();
        //调用布隆过滤器
        if (!clFilter.filter(analyzeBo.getClHash())) {
            //解析语言
            analyzeBo.setCl(clResolver.rsolver(uvrBo));
            clFilter.add(analyzeBo.getClHash());
        }
        if (!ipFilter.filter(analyzeBo.getIpHash())) {
            //解析IP
            analyzeBo.setIp(ipResolver.rsolver(uvrBo));
            ipFilter.add(analyzeBo.getIpHash());
        }
        if (!uaFilter.filter(analyzeBo.getUaHash())) {
            //解析UA记录
            analyzeBo.setUa(uaResolver.rsolver(uvrBo));
            uaFilter.add(analyzeBo.getUaHash());
        }
        return analyzeBo;
    }

    public InterceptSource getSource(AnalyzeBo uvrBo)
    {
        InterceptSource source = new InterceptSource();
        source.setCkf(uvrBo.getUvr().getCkf());
        source.setIp4(uvrBo.getUvr().getClientIp());
        source.setJa4(uvrBo.getUvr().getJa4());
        return source;
    }

}
